package cn.Mmovie.servlet;

import cn.Mmovie.bean.Administrator;
import cn.Mmovie.service.AdministratorService;
import cn.Mmovie.service.impl.AdministratorServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginValidateServlet", value = "/login_validate")
public class LoginValidateServlet extends HttpServlet {
    private AdministratorService administratorService=new AdministratorServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe=request.getParameter("rememberMe");
        String rememberPassword=request.getParameter("rememberPassword");
        Administrator admin = administratorService.loginAdmin(username,password);
        if (admin!=null){
            if (rememberMe!=null){
                Cookie usernameCookie=new Cookie("username",username);
                usernameCookie.setMaxAge(60*60*24*3);
                usernameCookie.setPath("/");
                response.addCookie(usernameCookie);
            }if (rememberPassword!=null){
                Cookie passwordCookie=new Cookie("password",password);
                passwordCookie.setMaxAge(60*60*24*3);
                passwordCookie.setPath("/");
                response.addCookie(passwordCookie);
            }
            request.getSession().setAttribute("admin",admin);
            response.sendRedirect(this.getServletContext().getContextPath()+"/admin/main");
        }else {
            request.setAttribute("failMsg","用户名或密码错误，请重试！");
            request.setAttribute("username",username);
            request.getRequestDispatcher("/login").forward(request,response);
        }
    }
}
